/**
 * Wihidum - Efficient Broker Hierarchy for Publish Subscribe Middleware
 *
 * License      :   Apache License 2.0
 * Home Page    :   http://code.google.com/p/wihidum/
 * Mailing List :   wihidum@googlegroups.com
 */

package lk.mrt.cse.wihidum.storage;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class BrokerList
{
        private static final Logger logger = Logger.getLogger (BrokerList.class);
        private static ArrayList<Broker> brokerList=new ArrayList<Broker>();
        public static ArrayList<Broker> shuffleAndReturnBrokerList()
        {
            Collections.shuffle(brokerList);
            logger.info("Top broker in admin service's list, after shuffling is"+brokerList.get(0).getAddress());
            ArrayList<Broker> subBrokerList=new ArrayList<Broker>();
            if((brokerList.size()>3)||(brokerList.size()==3))
            {
                for(int i=0;i<3;i++)
                {
                    Broker broker=brokerList.get(i);
                    subBrokerList.add(broker);
                    logger.info("The "+i+" broker in returned list, is"+broker.getAddress());
                }

            }
            else if(brokerList.size()<3)
            {
                subBrokerList.add(brokerList.get(0));
                logger.info("The returned broker is"+subBrokerList.get(0).getAddress());

            }

            return subBrokerList;
        }
        public static void addBrokerToList(Broker broker)
        {
            brokerList.add(broker);
        }
        public static void removeBrokerFromList(String brokerAddress)
        {
          if(!isEmpty())
          {
              Iterator it=brokerList.iterator();
              int i=0;
               while(it.hasNext())
               {
                   i++;
                   Broker currentBroker=(Broker)it.next();
                   if(currentBroker.getAddress().equals(brokerAddress))
                   {
                       it.remove();
                       brokerList.remove(i-1);
                   }
               }
          }
        }
        public static boolean isEmpty()
        {
            boolean empty=false;
            empty=brokerList.isEmpty();            
            return empty;
        }

}
